package com.mzba.place.ui;

import java.util.HashMap;

import org.json.JSONException;
import org.json.JSONObject;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Handler.Callback;
import android.os.Message;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

import com.google.gson.Gson;
import com.mzba.place.BasicActivity;
import com.mzba.place.R;
import com.mzba.place.db.SafeCardTable;
import com.mzba.place.db.UserTable;
import com.mzba.place.entity.RegisterEntity;
import com.mzba.place.utils.AppContext;
import com.mzba.place.utils.HttpUtils;
import com.mzba.place.utils.StringUtil;
import com.mzba.place.utils.UICore;
import com.mzba.place.utils.UrlConfig;
/**
 * Login Activity
 * @author 06peng
 *
 */
public class LoginActivity extends BasicActivity implements Callback {
	
	private Handler handler;
	
	private EditText etEmail;
	private EditText etPassword;
	private Button btnLogin;
	private Button btnRegister;
	
	private final int login = 0x10011;
	private final int login_error = 0x10012;

	@Override
	protected void onCreate(Bundle paramBundle) {
		super.onCreate(paramBundle);
		setContentView(R.layout.activity_login);
		handler = new Handler(this);
		etEmail = (EditText) findViewById(R.id.email_et);
		etPassword = (EditText) findViewById(R.id.passowrd_et);
		btnLogin = (Button) findViewById(R.id.login_btn);
		btnRegister = (Button) findViewById(R.id.register_btn);
		btnLogin.setOnClickListener(new View.OnClickListener() {
			
			@Override
			public void onClick(View v) {
				String email = etEmail.getText().toString().trim();
				String password = etPassword.getText().toString().trim();
				if (StringUtil.isBlank(email) || StringUtil.isBlank(password)) {
					Toast.makeText(LoginActivity.this, "email或者密码不能为空!", Toast.LENGTH_SHORT).show();
					return;
				}
				UICore.eventTask(LoginActivity.this, LoginActivity.this, login, null, true);
			}
		});
		btnRegister.setOnClickListener(new View.OnClickListener() {
			
			@Override
			public void onClick(View v) {
				startActivity(new Intent(LoginActivity.this, UpdateUserInfoActivity.class));
			}
		});
	}
	
	@Override
	public void execute(int mes, Object obj) {
		switch (mes) {
		case login:
			logout();
			break;
		}
	}
	
	private void logout() {
		String result = HttpUtils.delete(this, UrlConfig.sign_out);
		if (StringUtil.isNotBlank(result)) {
			int rc = getRc(result);
			if (rc == 0) {
				login();
			}
		}
	}
	
	private void login() {
		HashMap<String, String> paramsMap = new HashMap<String, String>();
//		paramsMap.put("auth_token", AppContext.getInstance().getAuthToken());
		
		paramsMap.put("user[email]", etEmail.getText().toString().trim());
		paramsMap.put("user[password]", etPassword.getText().toString().trim());
		String result = HttpUtils.doPost(this, UrlConfig.sign_in, paramsMap);
		if (result != null) {
			Gson gson = new Gson();
			RegisterEntity entity = gson.fromJson(result, RegisterEntity.class);
			if (entity != null) {
				String authToken = entity.getAuthentication_token();
				AppContext.getInstance().setAuthToken(authToken);
				UserTable ut = new UserTable(this);
				ut.save(entity);
				SafeCardTable st = new SafeCardTable(this);
				st.clearTable();
				handler.sendEmptyMessage(login);
			} else {
				handler.sendEmptyMessage(login_error);
			}
		} else {
			handler.sendEmptyMessage(login_error);
		}
	}
	
	private int getRc(String json) {
		JSONObject jsonObject;
		int rc = 1;
		try {
			jsonObject = new JSONObject(json);
			rc = jsonObject.getInt("rc");
		} catch (JSONException e) {
			e.printStackTrace();
		}
		return rc;
	}

	@Override
	public boolean handleMessage(Message msg) {
		switch (msg.what) {
		case login:
			Intent intent = new Intent(this, MainActivity.class);
			intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
			startActivity(intent);
			finish();
			break;
		case login_error:
			Toast.makeText(LoginActivity.this, "登录失败!", Toast.LENGTH_SHORT).show();
			break;
		}
		return false;
	}
	
	
}
